﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HZ.Supervise.Model;
using System.Text;
using HZ.Supervise.IBLL;
using System.Collections.Generic;
using HZ.Supervise.Web.Common;
using System.Threading;
using System.ComponentModel;
[assembly: WebResource("HZ.Supervise.Web.Scripts.ModalCommon.js", "text/javascript")]

namespace HZ.Supervise.Web.Secondphase
{
    public partial class hospitalAmountSubsidyDetailUn : BasePage
    {
        public string strHostpitalid = "";
        public string strProductId = "";
        string strPEssentialDrugsAmount = "";
        string text = "";
        string strPSubsidiesAmount = "";
        string strPSbsidyAmount = "";
        decimal PEssentialDrugsAmount = 0;
        decimal PSubsidiesAmount = 0;
        decimal PSbsidyAmount = 0;
        string PrescriptionID = "";
        string strhospitalid = "";
        string id = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            id = Request.QueryString["id"].ToString();
            if (id.Equals("0"))
            {
                btnFinish.Visible = false;
            }
            else
            {
                btnFinish0.Visible = false;
            }
            if (!IsPostBack)
            {

                banding();
            }
        }

        //绑定未补助的医院
        private void banding()
        {
            string remark = "";
            string zimu = Request.QueryString["PHospitalId"].ToString();
            strHostpitalid = zimu;
            remark = Request.QueryString["id"].ToString();
            int totalrecord = 0;
            HZ.Supervise.IBLL.IBLL_Prescription iPrescription = HZ.Supervise.BLLFactory.IBl_Prescription();
            string strwhere = "";
            strwhere += "and a.PSbsidyAmount<a.PSubsidiesAmount and POrderStatus =1  ";
            if (!strHostpitalid.Trim().Equals(""))//医院Id
            {
                strwhere += " and a.PHospitalId = '" + strHostpitalid + "'";
            }
            if (!txtPrescriptionName.Text.Trim().Equals(""))
            {
                strwhere += " and a.PrescriptionName  like '%" + txtPrescriptionName.Text.Trim() + "%'";
            }
            ////地区
            //if ("" != ddlCity.SelectedValue)
            //{

            //        strwhere += "and a.PAreaId='" + ddlCity.SelectedValue + "'";

            //}
            if (!txtStratTime.Text.Trim().Equals("")) //开始时间
            { strwhere += " and a.PSubmitTime >='" + (new HZ.Common.ConvertHelper(txtStratTime.Text.Trim()).ToDateTime).Value.ToString() + "'"; }
            if (!txtEndTime.Text.Trim().Equals("")) //结束时间
            { strwhere += " and a.PSubmitTime <='" + (new HZ.Common.ConvertHelper(txtEndTime.Text.Trim()).ToDateTime).Value.ToString() + "'"; }
            //医生名称
            if (!txtPdoctorName.Text.Trim().Equals(""))
            {
                strwhere += "and a.PdoctorName like'%" + txtPdoctorName.Text.Trim() + "%'";
            }
            //病人名称
            if (!txtPatientName.Text.Trim().Equals(""))
            {
                strwhere += "and  a.PatientName like'%" + txtPatientName.Text.Trim() + "%'";
            }
            //药品名称 通用名
            if (!txtproductname.Text.Trim().Equals(""))
            {
                strwhere += "and b.ProductName like'%" + txtproductname.Text.Trim() + "%'";
            }
            //流水号
            if (!txtProcureCatalogid.Text.Trim().Equals(""))
            {
                strwhere += "and b.ProcureCatalogID='%" + txtProcureCatalogid.Text.Trim() + "%'";
            }
            //规格
            if (!txtoutlookc.Text.Trim().Equals(""))
            {
                strwhere += "and b.Poutlookc like'%" + txtoutlookc.Text.Trim() + "%'";
            }
            //剂型
            if (!txtmedicineMoDelName.Text.Trim().Equals(""))
            {
                strwhere += " and b.PmedicineModelname like'%" + txtmedicineMoDelName.Text.Trim() + "%'";
            }
            if (!string.IsNullOrEmpty(strProductId))
            {
                strwhere += "and a.PrescriptionID not in (" + strProductId.TrimEnd(',') + ")";
            }
            DataTable dt = iPrescription.GetHospitalePrescrioDetail2(strwhere, this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageSize, out totalrecord);
            dt.Columns.Add("id");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["id"] = id;
            }
            AspNetPager1.RecordCount = totalrecord;
            this.gvwDetail.DataSource = dt;
            this.gvwDetail.DataBind();
            strProductId = "";


        }
        //public void BindArea()
        //{
        //    IBLL_Area ia = new HZ.Supervise.BLL.BLL_Area();
        //    IList<Area> lstArea = new List<Area>();
        //    string userAreaId = CurrentAccount.GetUser().Org.Area.AreaID;
        //    //判断用户所属地区，如果用户是省级的 则可以列出全部区域
        //    //if (userAreaId == CurrentAccount.GetCurrentDeployArea().AreaID)
        //    //{
        //    int i;
        //    lstArea = ia.GetSonAreas(userAreaId, 1, 0, out i);
        //    foreach (Area area in lstArea)
        //    {
        //        ListItem ddlitem = new ListItem();
        //        ddlitem.Text = area.AreaName;
        //        ddlitem.Value = area.AreaID;
        //        ddlCity.Items.Add(ddlitem);
        //    }

        //    ListItem b = new ListItem();
        //    b.Text = "全部";
        //    b.Value = "";
        //    ddlCity.Items.Insert(0, b);


        //}
        protected void btnFinish_Click(object sender, EventArgs e)
        {

            int nresult = 0;
            if (gvwDetail.Rows.Count > 0)
            {
                bool res = false; ;
                HZ.Supervise.IBLL.IBLL_Prescription iPrescription = HZ.Supervise.BLLFactory.IBl_Prescription();
                IList<Prescription> prescriptionList = new List<Prescription>();
                Subsidy subsidy = new Subsidy();
                string strstartime = "", strendtime = "";
                string userid = CurrentAccount.GetUser().UserID;
                StringBuilder sb = new StringBuilder();
                foreach (GridViewRow gdw in gvwDetail.Rows)
                {

                    CheckBox check = (CheckBox)gdw.Cells[0].FindControl("CheckBox1");
                    if (check.Checked)
                    {

                        string SubsidyID = Guid.NewGuid().ToString();
                        string strPrice = ((TextBox)gdw.FindControl("txtCount")).Text.Trim();//补助
                        if (string.IsNullOrEmpty(strPrice))
                        {
                            Response.Write("<script>alert('请填写补助金额！')</script>");
                            return;
                        }
                        string strbz = ((TextBox)gdw.FindControl("txtBZ")).Text.Trim();//备注
                        string strareid = ((Label)gdw.FindControl("PAreaId")).Text.Trim();
                        string strarename = ((Label)gdw.FindControl("PAreaname")).Text.Trim();
                        string strhospitname = ((Label)gdw.FindControl("PHospitalName")).Text.Trim();
                        string strhospitalid = ((Label)gdw.FindControl("PHospitalId")).Text.Trim();
                        string strPEssentialDrugsAmount = ((Label)gdw.FindControl("PtotalAmount")).Text.Trim();
                        //应补助金额
                        string strPSubsidiesAmount = ((Label)gdw.FindControl("PSubsidiesAmount")).Text.Trim();
                        //已补助金额
                        string strPSbsidyAmount = ((Label)gdw.FindControl("PSbsidyAmount")).Text.Trim();
                        string PrescriptionID = ((Label)gdw.FindControl("PrescriptionID")).Text.Trim();
                        string strwhere1 = "and PrescriptionID='" + PrescriptionID + "'";
                        strstartime = gdw.Cells[4].Text.Trim();
                        decimal price = Convert.ToDecimal(strPrice);
                        //已补助金额
                        decimal PEssentialDrugsAmount = Convert.ToDecimal(strPSbsidyAmount);
                        decimal PSubsidiesAmount = Convert.ToDecimal(strPSubsidiesAmount);
                        if ((price + PEssentialDrugsAmount) > PSubsidiesAmount)
                        {
                            Response.Write("<script>alert('补助金额不能大于应补助金额！')</script>");
                            return;
                        }
                        strendtime = DateTime.Now.ToString();
                        string title = "";
                        if (!txtRatio3.Text.Trim().Equals(""))
                        {
                            title = txtRatio3.Text.Trim();
                        }
                        else
                        {
                            title = CurrentAccount.GetUser().UserName + DateTime.Now.ToString("yyyyMMddHHmmss") + "结算单";
                        }
                        DataTable dt2 = iPrescription.GetHospitaleTB_Prescription(strwhere1);
                        if (!strPrice.Equals(""))//是否空
                        {
                            if (dt2.Rows.Count > 0)
                            {
                                if (string.IsNullOrEmpty(strstartime))
                                {
                                    strstartime = dt2.Rows[0]["PSubmitTime"].ToString();
                                }
                                //处方单中应补助金额
                                decimal prePSubsidiesAmount = Convert.ToDecimal(dt2.Rows[0]["PSubsidiesAmount"].ToString());
                                //处方单中的已补助金额
                                decimal prePSbsidyAmount = Convert.ToDecimal(dt2.Rows[0]["PSbsidyAmount"].ToString());
                                //判断处方单中是否有已补助金额
                                if (prePSbsidyAmount > 0)
                                {
                                    Prescription prescription = new Prescription();
                                    //算出未补贴金额
                                    decimal UnPSbsidyAmount = prePSubsidiesAmount - prePSbsidyAmount;
                                    //若未补助金额大于补贴金额
                                    if (UnPSbsidyAmount > price)
                                    {
                                        prescription.POrderStatus = 2;
                                        //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                        prescription.PSbsidyAmount = prePSbsidyAmount + price;
                                        prescription.PSubmitTime = DateTime.Now;
                                        prescription.PSubsidyUserid = userid;
                                        prescription.PrescriptionId = dt2.Rows[0]["PrescriptionId"].ToString();
                                        prescriptionList.Add(prescription);
                                        price = 0;
                                    }
                                    else
                                    {
                                        prescription.POrderStatus = 2;
                                        //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                        prescription.PSbsidyAmount = prePSubsidiesAmount;
                                        prescription.PSubmitTime = DateTime.Now;
                                        prescription.PSubsidyUserid = userid;
                                        prescription.PrescriptionId = dt2.Rows[0]["PrescriptionId"].ToString();
                                        prescriptionList.Add(prescription);
                                        price = price - UnPSbsidyAmount;
                                    }

                                }
                                else
                                {
                                    Prescription prescription = new Prescription();
                                    //添加以补助金额为0的数据
                                    if (prePSbsidyAmount <= 0)
                                    {

                                        //id
                                        subsidy.SubsidyID = SubsidyID;
                                        //地区Id
                                        subsidy.Sareaid = Convert.ToInt32(strareid);
                                        //地区名称
                                        subsidy.Sareaname = strarename;
                                        //医院Id
                                        subsidy.SHospitalID = strhospitalid;
                                        //医院名称
                                        subsidy.SHospitalName = strhospitname;
                                        //总金额
                                        subsidy.SsumAmount = Convert.ToDecimal(strPEssentialDrugsAmount);
                                        //已补贴总金额
                                        subsidy.SubsidyAmount = Convert.ToDecimal(strPrice);
                                        //补贴添加时间
                                        subsidy.Saddtime = DateTime.Now;
                                        //补贴人
                                        subsidy.Sadduserid = userid;
                                        //处方单开始时间
                                        subsidy.SubsidyStartTime = Convert.ToDateTime(strstartime);
                                        //处方单结束时间
                                        subsidy.SubsidyEndTime = Convert.ToDateTime(strendtime);
                                        //备注信息
                                        subsidy.Remark = strbz;
                                        //状态
                                        subsidy.State = 0;
                                        //结算单名称
                                        subsidy.SubsidyName = title;
                                        //应补贴金额
                                        subsidy.Amount = Convert.ToDecimal(strPSubsidiesAmount);
                                        //处方单应补助金额大于补助金额
                                        if (prePSubsidiesAmount > price)
                                        {

                                            prescription.POrderStatus = 2;
                                            //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                            prescription.PSbsidyAmount = prePSbsidyAmount + price;
                                            prescription.PSubmitTime = DateTime.Now;
                                            prescription.PSubsidyUserid = userid;
                                            prescription.PrescriptionId = dt2.Rows[0]["PrescriptionId"].ToString();
                                            prescriptionList.Add(prescription);
                                            string gu = Guid.NewGuid().ToString();
                                            price = 0;
                                        }
                                        else
                                        {
                                            prescription.POrderStatus = 2;
                                            //当前补贴金额 小于未补助金额时，用未补贴金额减去用户所填金额，加上已补贴金额
                                            prescription.PSbsidyAmount = prePSubsidiesAmount;
                                            prescription.PSubmitTime = DateTime.Now;
                                            prescription.PSubsidyUserid = userid;
                                            prescription.PrescriptionId = dt2.Rows[0]["PrescriptionId"].ToString();
                                            prescriptionList.Add(prescription);
                                            price = price - prePSubsidiesAmount;
                                        }

                                    }
                                }

                            }
                        }

                        nresult = iPrescription.UpdateAll(subsidy, prescriptionList, 0);
                        if (nresult > 0)
                        {
                            Response.Write("<script>alert('补贴发放成功！')</script>");

                        }
                        else
                        {
                            Response.Write("<script>alert('补贴发放失败！')</script>");
                        }
                        banding();
                        res = true;
                    }
                    //else 
                    //{
                    //    Response.Write("<script>alert('医院已撤单！')</script>");
                    //    banding();

                    //}

                }
                if (!res)
                {

                    Response.Write("<script>alert('没有要发放的补贴！')</script>");
                }
            }
        }


        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            banding();
        }

        protected void gvwDetail_RowCommand(object sender, GridViewCommandEventArgs e)
        {

        }
        //查询
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            banding();
        }
        //高级查询
        protected void lbnSwitch_Click(object sender, EventArgs e)
        {
            if (lbnSwitch.CommandArgument == "simple")
            {
                ltlAdvance.Text = "";
                lbnSwitch.CommandArgument = "advance";
                lbnSwitch.Text = "简单查询";
            }
            else
            {
                ltlAdvance.Text = "<tbody id='advance' style='display:none'>";
                lbnSwitch.CommandArgument = "simple";
                lbnSwitch.Text = "高级查询";

                //清空数据
                txtProcureCatalogid.Text = "";
                txtproductname.Text = "";
                txtmedicineMoDelName.Text = "";
                txtoutlookc.Text = "";
            }
        }
        /// <summary>
        /// 批量发放补助
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void HzButton1_Click(object sender, EventArgs e)
        {

            banding();
        }

        protected void HzButton2_Click(object sender, EventArgs e)
        {
            bool res = false;

            strhospitalid = Request.QueryString["PHospitalId"].ToString();
            text = txtRatio3.Text;
            for (int i = 0; i < gvwDetail.Rows.Count; i++)
            {
                CheckBox check = (CheckBox)gvwDetail.Rows[i].FindControl("CheckBox1");
                if (check.Checked)
                {
                    strPEssentialDrugsAmount = ((Label)gvwDetail.Rows[i].FindControl("PtotalAmount")).Text.ToString();
                    PEssentialDrugsAmount += Convert.ToDecimal(strPEssentialDrugsAmount);
                    //应补助金额
                    strPSubsidiesAmount = ((Label)gvwDetail.Rows[i].FindControl("PSubsidiesAmount")).Text.ToString();
                    PSubsidiesAmount += Convert.ToDecimal(strPSubsidiesAmount);
                    //已补助金额
                    strPSbsidyAmount = ((Label)gvwDetail.Rows[i].FindControl("PSbsidyAmount")).Text.ToString();
                    PSbsidyAmount += Convert.ToDecimal(strPSbsidyAmount);
                    PrescriptionID += ((Label)gvwDetail.Rows[i].FindControl("PrescriptionID")).Text.ToString() + ",";
                    res = true;
                }

            }
            string PAreaId = Request.QueryString["PAreaId"].ToString();
            if (!res)
            {
                Response.Write("<script>alert('没有要发放的补贴！')</script>");
                return;
            }
            else
            {

                string[] PrescriptionIDs = PrescriptionID.TrimEnd(',').Split(',');
                for (int i = 0; i < PrescriptionIDs.Length; i++)
                {
                    strProductId += "'" + PrescriptionIDs[i] + "',";
                }
                banding();

                Response.Redirect("CheckHospitalAmount.aspx?id=" + PrescriptionID + "&PEssentialDrugsAmount=" + PEssentialDrugsAmount + "&PSubsidiesAmount=" + PSubsidiesAmount + "&PSbsidyAmount=" + PSbsidyAmount + "&text=" + text + "&PHospitalId=" + strhospitalid + "&PAreaId=" + PAreaId, true);
                //    this.Page.RegisterStartupScript("", "<script>window.showModalDialog('CheckHospitalAmount.aspx?id=" + PrescriptionID + "&PEssentialDrugsAmount=" + PEssentialDrugsAmount + "&PSubsidiesAmount=" + PSubsidiesAmount + "&PSbsidyAmount=" + PSbsidyAmount + "&text=" + text + "&PHospitalId=" + strhospitalid+",'window',dialogWidth:320px,dialogHeight:335px,dialogTop:200px,dialogLeft,200px ");

                //    ////Page.ClientScript.RegisterClientScriptResource(this.GetType(), "HZ.Supervise.Web.Scripts.ModalCommon.js");
                //    ////string JsUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "HZ.Supervise.Web.Scripts.ModalCommon.js");
                //    ////Page.Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\" javascript:showPopWin('批量发放','CheckHospitalAmount.aspx?id=" + PrescriptionID + "&PEssentialDrugsAmount=" + PEssentialDrugsAmount + "&PSubsidiesAmount=" + PSubsidiesAmount + "&PSbsidyAmount=" + PSbsidyAmount + "&text=" + text + "&PHospitalId=" + strhospitalid + "', 900,450, null,true,true) ></script>"));

            }

        }

        protected void btnFinish1_Click(object sender, EventArgs e)
        {
            //string PHospitalId = Request.QueryString["PHospitalId"].ToString();
            //string PEssentialDrugsAmount = Request.QueryString["PEssentialDrugsAmount"].ToString();
            //string PAreaId = Request.QueryString["PAreaId"].ToString();
            Response.Redirect(string.Format("hospitalAmountSubsidy.aspx"), true);
        }
        /// <summary>
        /// 呈现前预处理
        /// </summary>
        /// <param name="e"></param>
        //protected override void OnPreRender(EventArgs e)
        //{
        //    if (!Page.ClientScript.IsClientScriptBlockRegistered("AreaControls_PCASClass"))
        //    {
        //        //注册脚本库
        //        string jsResource = Page.ClientScript.GetWebResourceUrl(typeof(hospitalAmountSubsidyDetailUn), "HZ.Supervise.Web.Common.Resource.ModalCommon.js");
        //        Page.ClientScript.RegisterClientScriptInclude(typeof(string), "AreaControls_PCASClass", jsResource);

        //    }

        //    StringBuilder sb = new StringBuilder("<script language=\"Javascript\"><!--\n");
        //    sb.Append("javascript:initPopUp();");
        //    sb.Append("\n--></script>\n");

        //    if (!Page.ClientScript.IsStartupScriptRegistered("areaControls_key"))
        //    {
        //        Page.ClientScript.RegisterStartupScript(typeof(string), "areaControls_key", sb.ToString());
        //    }
        //    base.OnPreRender(e);
        //    }
    }
}
